/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.starmeep.server;

import com.jcraft.jsch.JSchException;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.starmeep.classes.StarCluster;
import org.starmeep.classes.StarJob;
import org.starmeep.classes.StarMeep;
import org.starmeep.config.ConfigStarCluster;

/**
 *
 * @author CARLOS
 */
public class GWTUpLoadFile extends HttpServlet {
   String directoryCONF="/root/";
   String directoryCTL="/tmp/";
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text;charset=UTF-8");
        String option=request.getParameter("op");
        PrintWriter out = response.getWriter();

        if(option.equals("fileCONF"))
        {
            String fileName=getNSaveFile(request,directoryCONF,"keyLocation");
            System.out.print(fileName);
            try {
                if(!fileName.equals("error"))
                    out.print(fileName);
                else
                    out.print("File Key Location upload is failed");
            } finally {
                out.close();
            }
        }
        if(option.equals("fileCTL"))
        {
            StarCluster starcluster=(StarCluster) request.getSession().getAttribute("starcluster");
            StarMeep sm = null;
            try {
                System.out.println("host: "+starcluster.getHostmaster());
                sm = new StarMeep(request.getParameter("nameJob"), starcluster, Integer.parseInt(request.getParameter("size")));
            } catch (JSchException ex) {
                Logger.getLogger(GWTUpLoadFile.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InterruptedException ex) {
                Logger.getLogger(GWTUpLoadFile.class.getName()).log(Level.SEVERE, null, ex);
            }

            Map mpJobs=(Map)request.getSession().getAttribute("Jobs");
            StarJob job= new StarJob();
            String fileName=getNSaveFile(request,directoryCTL,"fileCtl");
            String nameJob=request.getParameter("nameJob");
            String param=request.getParameter("param");
            String size=request.getParameter("size");
            job.setName(nameJob);
            job.setParameters(param);
            job.setFileCtlname(fileName);
            job.setSizeNodes(Integer.parseInt(size));
            job.setMeep(sm);

            //upload CTL to master
            

            
            try {
                if(!fileName.equals("error"))
                {

                    System.out.println("Antes de entrar a copiar el archiv con el directorio:"+directoryCTL+fileName);
                    sm.uploadCTL(new File(directoryCTL, fileName),fileName);

                    if(mpJobs==null)
                        mpJobs=new HashMap();
                    mpJobs.put(job.getName(), job);
                    request.getSession().setAttribute("Jobs",mpJobs);
                    out.print(fileName);
                }
                else
                    out.print("");
            } finally {
                out.close();
            }
        }
        if(option.equals("fileUploadCONF"))
        {
            String fileName=getNSaveFile(request,directoryCTL,"flFileLoad");
             try {
                if(!fileName.equals("error"))
                {
                    ConfigStarCluster config=ConfigStarCluster.readConfigFromFile(directoryCTL+fileName);
                    request.getSession().setAttribute("configLoad", config);
                    out.print("fileUploadCONF");
                    System.out.println("Salida del upload");
                }
                else
                    out.print("");
            }
            catch(Exception e){
                    System.out.println(e.getMessage());
            }
             finally {
                out.close();
            }
        }
    }
    public String getNSaveFile(HttpServletRequest request,String directory,String field) {
        String fileName="";
        try {
            // Chequea que sea un request multipart (que se este enviando un file)
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            System.out.println("Is multipart="+isMultipart);

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maxima talla que sera guardada en memoria
            factory.setSizeThreshold(4096);
            // si se excede de la anterior talla, se ira guardando temporalmente, en la sgte direccion
            factory.setRepository(new File(directory));
            ServletFileUpload upload = new ServletFileUpload(factory);
            //maxima talla permisible (si se excede salta al catch)
            upload.setSizeMax(10000000);
            List fileItems = upload.parseRequest(request);
            //obtiene el file enviado
            Iterator i = fileItems.iterator();
            FileItem fi=null;
            while (i.hasNext()) {
                 fi = (FileItem) i.next();
                 if(fi.getFieldName().contains(field))
                     break;
            }
            //graba el file enviado en el servidor local
            //path y Nombre del archivo destino (en el server)
            String path=directory;
            fileName=fi.getName();
            fi.write(new File(path, fileName));
            }
        catch(Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
             return "error";
            }
        return fileName;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
